package com.example.demo;

import com.example.demo.httpMessageConvert.Property;
import com.example.demo.httpMessageConvert.SessionKey;
import com.example.demo.httpMessageConvert.UrlKey;
import com.example.demo.integration.SampleMessageGateway;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.csource.common.MyException;
import org.csource.fastdfs.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.security.Principal;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/7/31.
 */
@Controller
@RequestMapping("test")
public class TestController {
    private static final Logger logger = LogManager
            .getLogger(TestController.class);
    @Autowired
    private Property property;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SampleMessageGateway sampleMessageGateway;

    @RequestMapping(value = "home", method = {RequestMethod.POST, RequestMethod.GET})
    public String weixinGet(String access_token, Model model, HttpSession httpSession, HttpServletRequest httpServletRequest,Principal principal, HttpServletResponse httpServletResponse,String code,String state) throws IOException {
        if (httpSession.getAttribute(SessionKey.USER_INFO) != null) {
            return "home";
        } else {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair(UrlKey.APPID, property.getAppid()));
            params.add(new BasicNameValuePair(UrlKey.REDIRECT_URI, property.getRedirect_uri()));
            params.add(new BasicNameValuePair(UrlKey.RESPONSE_TYPE, property.getResponse_type()));
            String randomAlphanumeric = RandomStringUtils.randomAlphanumeric(128);
            params.add(new BasicNameValuePair(UrlKey.STATE, randomAlphanumeric));
            params.add(new BasicNameValuePair(UrlKey.SCOPE, "snsapi_userinfo"));
            // model.addAttribute("url", property.getAuthorize() + "?" + URLEncodedUtils.format(params, Charset.forName("UTF-8")));
            httpServletResponse.sendRedirect(property.getAuthorize() + "?" + URLEncodedUtils.format(params, Charset.forName("UTF-8")));
            return null;
        }
    }

    @RequestMapping(value = "test", method = {RequestMethod.POST, RequestMethod.GET})
    public void weixinGet(Model model, HttpSession httpSession, HttpServletResponse httpServletResponse) throws IOException {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("client_id", "e2d7af3de339e91b7677"));
        params.add(new BasicNameValuePair("scope", "user"));
        params.add(new BasicNameValuePair("state", RandomStringUtils.randomAlphanumeric(5)));
        httpServletResponse.sendRedirect("https://github.com/login/oauth/authorize"+ "?" + URLEncodedUtils.format(params, Charset.forName("UTF-8")));;


    }

    @RequestMapping("/")
    public String email(Principal principal) {
        return "Hello " + principal.getName();
    }

    @RequestMapping(value = "/upload", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String email(MultipartFile file) throws MyException, IOException {
        ClassPathResource classPathResource=new ClassPathResource("fdfs_client.conf");
        ClientGlobal.init(classPathResource.getClassLoader().getResource("fdfs_client.config").getPath());
        TrackerClient trackerClient=new TrackerClient();
        TrackerServer trackerServer=trackerClient.getConnection();
        StorageServer storageServer=null;
        StorageClient1 storageClient=new StorageClient1(trackerServer,storageServer);
        String substring = file.getContentType().substring(file.getContentType().lastIndexOf("/") + 1);
        String s = storageClient.upload_file1(file.getBytes(), substring, null);
       return s;

    }

    @Autowired
    private GridFsTemplate gridFsTemplate;


    @PostMapping(path = "/test")
    public void test(MultipartFile multipartFile, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
        InputStream inputStream = multipartFile.getInputStream();
        ObjectId objectId = gridFsTemplate.store(inputStream,multipartFile.getOriginalFilename());
        String string = objectId.toString();
        GridFSFile test1 = gridFsTemplate.findOne(Query.query(GridFsCriteria.where("_id").is(string)));
        GridFsResource resource = gridFsTemplate.getResource(test1);
        byte[] bytes = FileCopyUtils.copyToByteArray(resource.getInputStream());
        httpServletResponse.getWriter().write(new String(bytes));

    }
    @GetMapping(path = "/getPitture")
    public void getPitture( HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
        GridFSFile test1 = gridFsTemplate.findOne(Query.query(GridFsCriteria.where("_id").is("5b2a112d5da57c293c7b9c30")));
        GridFsResource resource = gridFsTemplate.getResource(test1);
        byte[] bytes = FileCopyUtils.copyToByteArray(resource.getInputStream());
        httpServletResponse.getOutputStream().write(bytes);
        httpServletResponse.getOutputStream().close();

    }

}
